<script setup lang="ts">
import { ref, watch, h } from 'vue';
import { NDrawer, NDataTable, NTag, NButton, NSpace, NModal, useMessage } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
import { fetchDevInstanceList, stopExecution, type DevTask, type DevInstance } from '@/service/api/dataplatform/dev';

interface Props {
  visible: boolean;
  task: DevTask | null;
}

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const message = useMessage();
const loading = ref(false);
const instanceList = ref<DevInstance[]>([]);
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
});

const logModalVisible = ref(false);
const currentLogs = ref('');

// 表格列定义
const columns: DataTableColumns<DevInstance> = [
  { title: '实例ID', key: 'id', width: 100 },
  {
    title: '状态',
    key: 'status',
    width: 120,
    render: (row) => {
      const statusMap: Record<string, { label: string; type: any }> = {
        RUNNING: { label: '运行中', type: 'info' },
        SUCCESS: { label: '成功', type: 'success' },
        FAILED: { label: '失败', type: 'error' },
        STOPPED: { label: '已停止', type: 'warning' }
      };
      const config = statusMap[row.status] || { label: row.status, type: 'default' };
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  { title: '开始时间', key: 'startTime', width: 180 },
  { title: '结束时间', key: 'endTime', width: 180 },
  {
    title: '执行时长',
    key: 'duration',
    width: 120,
    render: (row) => (row.duration ? `${(row.duration / 1000).toFixed(2)}s` : '-')
  },
  { title: '结果行数', key: 'resultRows', width: 100 },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    fixed: 'right',
    render: (row) => {
      const buttons = [];
      if (row.logs) {
        buttons.push(
          h(NButton, { size: 'small', onClick: () => handleViewLogs(row) }, { default: () => '查看日志' })
        );
      }
      if (row.status === 'RUNNING') {
        buttons.push(
          h(NButton, { size: 'small', type: 'warning', onClick: () => handleStop(row.id) }, { default: () => '停止' })
        );
      }
      return h(NSpace, null, { default: () => buttons });
    }
  }
];

// 加载实例列表
async function loadInstances() {
  if (!props.task) return;

  loading.value = true;
  try {
    const params = {
      pageNum: pagination.value.page,
      pageSize: pagination.value.pageSize
    };
    const res = await fetchDevInstanceList(props.task.id!, params);
    if (res.data) {
      instanceList.value = res.data.rows || [];
      pagination.value.itemCount = res.data.total || 0;
    }
  } catch (error) {
    message.error('加载实例列表失败');
  } finally {
    loading.value = false;
  }
}

// 查看日志
function handleViewLogs(instance: DevInstance) {
  currentLogs.value = instance.logs || instance.errorMsg || '暂无日志';
  logModalVisible.value = true;
}

// 停止执行
async function handleStop(instanceId: number) {
  try {
    await stopExecution(instanceId);
    message.success('停止成功');
    loadInstances();
  } catch (error) {
    message.error('停止失败');
  }
}

// 分页变化
function handlePageChange(page: number) {
  pagination.value.page = page;
  loadInstances();
}

function handlePageSizeChange(pageSize: number) {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  loadInstances();
}

// 关闭抽屉
function handleClose() {
  emit('update:visible', false);
}

// 监听visible变化
watch(
  () => props.visible,
  val => {
    if (val) {
      pagination.value.page = 1;
      loadInstances();
    }
  }
);
</script>

<template>
  <NDrawer :show="visible" :width="1000" @update:show="handleClose">
    <n-drawer-content :title="`任务实例 - ${task?.name || ''}`" closable>
      <NDataTable
        :columns="columns"
        :data="instanceList"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1000"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </n-drawer-content>
  </NDrawer>

  <!-- 日志弹窗 -->
  <NModal v-model:show="logModalVisible" preset="card" title="执行日志" style="width: 800px">
    <pre class="bg-gray-50 p-12px rounded text-12px overflow-auto max-h-400px">{{ currentLogs }}</pre>
  </NModal>
</template>

<style scoped></style>
